package pl.peterjack.servlet.dane.klient;

import java.io.IOException;

import javax.jdo.PersistenceManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import pl.peterjack.model.PMF;
import pl.peterjack.model.dane.Firma;
import pl.peterjack.model.dane.Klient;
import pl.peterjack.model.dane.RezultatOdpowiedz;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.impl.LogFactoryImpl;

import com.google.gson.Gson;

/**
 * Zwraca adane dla generowania faktury, kiedy user wybierze klienta, 
 * powoduje to wpisanie w polach jego danych
 * @author peterjack
 *
 */
public class KlientDane extends HttpServlet {
	
	Log log = new LogFactoryImpl().getInstance( getClass() );

	@Override 
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		PersistenceManager pm = PMF.get().getPersistenceManager();
	    Firma firma = (Firma) req.getSession().getAttribute("firma");
	    Long id = Long.parseLong((String)req.getParameter("id")); 
	    Klient klient = pm.getObjectById(Klient.class, id);
	    Gson gson = new Gson();
	    RezultatOdpowiedz result = new RezultatOdpowiedz();
	    if(!klient.getFirma().equals(firma.getId())) {
	    	result.setSuccess(false);
		    resp.setCharacterEncoding("UTF-8");
	        resp.getWriter().println(gson.toJson(result));
	    	return; 
	    }
	    try {
	    	klient.setHaslo(""); 
	    	result.setSuccess(true);
	    	result.setData( klient );
        } catch(Exception e) {
        	e.printStackTrace(); 
        	result.setSuccess(false);
        } finally {
            pm.close();
		    resp.setCharacterEncoding("UTF-8");
            resp.getWriter().println(gson.toJson(result));
        }
	    //resp.setContentType("application/json");
	}

}	

